!function(){
    var $$ = Dom7;

    var Audioapp = new Framework7({
        animateNavBackIcon: true,
        template7Pages:true
    });

    var mainView = Audioapp.addView('.view-main', {dynamicNavbar: true});

    Audioapp.PanelTemplate = Template7.compile($$('script#Panel').html());
    Audioapp.NoteTemplate = Template7.compile($$('script#Note').html());

    $$(document).on('click','.closenote-btn',function () {
        mainView.router.back();
    });

    $$.ajax({
        url:'http://api.nldou.com/weixinapi/init_wx_jsapi',
        method:"GET",
        data: {fromUrl:window.location.href},
        dataType:'json',
        success: function (res) {
            //console.log('初始化jssdk',res);
            if(res.code==1){
                wx.config({
                    debug: false,
                    appId: res.data.appid,
                    timestamp: res.data.timestamp,
                    nonceStr: res.data.nonceStr,
                    signature: res.data.signature,
                    jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage','hideMenuItems']
                });
            }
        }
    });

    wx.ready(function () {
        wx.hideMenuItems({
            menuList: ['menuItem:share:qq','menuItem:share:weiboApp','menuItem:share:facebook','menuItem:share:QZone',
                'menuItem:copyUrl','menuItem:openWithQQBrowser','menuItem:openWithSafari']
        });
        var query = window.location.search;
        var qidstartpos = query.indexOf('qid=')+4;
        var qidendpos = query.indexOf('uid=')-1;
        var uidstartpos = query.indexOf('uid=')+4;
        var audioqid = query.substring(qidstartpos,qidendpos);
        var Globaluid = query.substr(uidstartpos);
        var shareobj = {url:'',title:''};
        shareobj.url = 'http://api.nldou.com/ucenter/weixinlogin?pid=7653&page=question&param=qid.'+audioqid;
        var audiosrc,audiotitle,audionum,audionote;

        function sharecallback(sharetype)
        {
            $$.ajax({
                method: 'POST',
                url: 'http://api.nldou.com/commwapucenter/sharecallback',
                data: {uid:Globaluid,url:shareobj.url,type:sharetype},
                dataType: 'json',
                success: function (res) {return true;}
            });
        }

        $$.ajax({
            method:'POST',
            url:'http://api.nldou.com/commwapaudio/getMultiAudio',
            data:{qid:audioqid},
            dataType:'json',
            async:false,
            success:function (res) {
                //console.log('音频页面',res);
                if (res.code==1){
                    audiosrc = res.data.audios;
                    audiotitle = res.data.titles;
                    audionum = res.data.audios.length;
                    audionote = res.data.notes;
                    shareobj.title = res.data.title;
                    $$('#Audio .audiotitle').html(audiotitle[0]);
                    var panelhtml = Audioapp.PanelTemplate(audiotitle);
                    $$('.panel-right').html(panelhtml);
                }
            }
        });

        var audioindex=0;
        var sound = [];
        var barlength = Math.ceil($$('.slidebar').width());//拖拽轴的长度
        var startpos = 0;//拖拽开始的位置，相对于拖拽轴的左端，单位px
        var endpos = 0;//拖拽结束的位置，相对于拖拽轴的左端，单位px
        var startpagex;//拖拽开始的位置，相对于屏幕的左端，单位px
        var audioplaying = false;//音频的播放状态
        var audiocounter;//计时器
        var curtime = 0;
        var tpx,pxt,min,sec;

        var audioanimid;
        function audioanim(){
            var r = parseFloat($$("#Audio .audiocover").data('rotate'));
            r = r>360?(r-360+0.2):(r+0.2);
            $$("#Audio .audiocover").transform('rotate('+r+'deg)');
            $$("#Audio .audiocover").data('rotate',r);
            audioanimid = $$.requestAnimationFrame(audioanim);
        }
        function initprobar()
        {
            tpx = sound[audioindex].duration/barlength;//(s/px)
            pxt = barlength/sound[audioindex].duration;//(px/s)
            //格式化总时间
            min = Math.floor(sound[audioindex].duration/60).toString();
            min = min.length>1?min:'0'+min;
            sec = Math.round(sound[audioindex].duration%60).toString();
            sec = sec.length>1?sec:'0'+sec;
            $$('.totaltime').html(min+':'+sec);
            $$('.audiotitle').html(audiotitle[audioindex]);
            $$("#Audio .slide-btn span").hide();
        }
        function skiptonext() {
            if (sound[audioindex].isload){
                audioindex++;
                if (audioindex>audionum-1) {
                    audioindex--;
                }else{
                    if (sound[audioindex].isload){
                        sound[audioindex-1].howl.stop();
                        initprobar();
                        sound[audioindex].howl.play();
                        $$('.skipitem.active').removeClass('active');
                        $$('.skipitem').eq(audioindex).addClass('active');
                    }else{
                        audioindex--;
                    }
                }
            }
        }
        function skiptoprev() {
            if (sound[audioindex].isload){
                audioindex--;
                if (audioindex<0) {
                    audioindex++;
                }else{
                    if (sound[audioindex].isload){
                        sound[audioindex+1].howl.stop();
                        initprobar();
                        sound[audioindex].howl.play();
                        $$('.skipitem.active').removeClass('active');
                        $$('.skipitem').eq(audioindex).addClass('active');
                    }else{
                        audioindex++;
                    }
                }
            }
        }
        function skipto(index) {
            if (sound[index].isload){
                sound[audioindex].howl.stop();
                audioindex=index;
                initprobar();
                sound[index].howl.play();
            }
        }

        audiosrc.forEach(function (value,index) {
            var sitem={isload:false,howl:null,duration:0};
            sitem.howl = new Howl({
                src:value,
                html5:true,
                onload:function () {
                    sitem.duration = sitem.howl.duration();
                    sitem.isload = true;
                    if (index==0) initprobar();
                },
                onplay:function () {
                    audioplaying = true;
                    $$(".play-btn").find('i').html('pause_round');
                    audiocounter = setInterval(function () {
                        curtime++;
                        //格式化时间
                        min = Math.floor(curtime/60).toString();
                        min = min.length>1?min:'0'+min;
                        sec = Math.round(curtime%60).toString();
                        sec = sec.length>1?sec:'0'+sec;
                        $$('.curtime').html(min+':'+sec);
                        endpos = pxt*curtime;
                        $$('.probar').css('width', endpos + 'px');
                    },1000);
                    audioanimid = $$.requestAnimationFrame(audioanim);
                },
                onpause:function () {
                    audioplaying=false;
                    clearInterval(audiocounter);
                    $$(".play-btn").find('i').html('play_round');
                    $$.cancelAnimationFrame(audioanimid);
                },
                onstop:function () {
                    audioplaying=false;
                    clearInterval(audiocounter);
                    $$(".play-btn").find('i').html('play_round');
                    curtime = 0;
                    $$('.curtime').html('00:00');
                    endpos = 0;
                    $$('.probar').css('width', endpos + 'px');
                    $$.cancelAnimationFrame(audioanimid);
                },
                onend:function () {
                    audioplaying=false;
                    clearInterval(audiocounter);
                    $$(".play-btn").find('i').html('play_round');
                    curtime = 0;
                    $$('.curtime').html('00:00');
                    endpos = 0;
                    $$('.probar').css('width', endpos + 'px');
                    $$.cancelAnimationFrame(audioanimid);
                    skiptonext();
                },
                onseek:function () {
                    sitem.howl.play();
                }
            });
            sound.push(sitem);
        });
        //打开播放列表
        $$('.audio-list-btn').on('click',function () {
            Audioapp.openPanel('right');
        });
        //打开笔记
        $$('.audio-info-btn').on('click',function () {
            var html=Audioapp.NoteTemplate(audionote);
            mainView.router.load({url:'audiopre.html',context:{note:html}});
        });
        //播放列表跳转
        $$('.skipitem').on('click',function () {
            if(!$$(this).hasClass('active')){
                var i = $$(this).data('index');
                if (sound[i].isload){
                    $$('.skipitem.active').removeClass('active');
                    $$(this).addClass('active');
                    skipto(i);
                    Audioapp.closePanel();
                }
            }
        });

        //播放/暂停
        $$(".play-btn").on('click',function () {
            if (sound[audioindex].isload){
                if (!audioplaying){
                    sound[audioindex].howl.play();
                }else{
                    sound[audioindex].howl.pause();
                }
            }
        });
        $$(".skip-prev-btn").on('click',function () {
            skiptoprev();
        });
        $$(".skip-next-btn").on('click',function () {
            skiptonext();
        });
        //拖拽时间轴
        $$(".slide-btn").on('touchstart',function(e){
            if (sound[audioindex].isload){
                sound[audioindex].howl.pause();
                startpos = endpos;
                startpagex = e.touches[0].pageX;
            }
        });
        $$(".slide-btn").on('touchmove',function(e){
            if (sound[audioindex].isload) {
                var p = e.touches[0].pageX - startpagex + startpos;
                if (p > 0 && p < barlength) {
                    endpos = p;
                    $$(this).parent().css('width', endpos + 'px');

                    curtime = endpos * tpx;
                    var min = Math.floor(curtime / 60).toString();
                    min = min.length>1?min:'0'+min;
                    var sec = Math.round(curtime % 60).toString();
                    sec = sec.length > 1 ? sec : '0' + sec;
                    $$('.curtime').html(min + ':' + sec);
                }
            }
        });
        $$(".slide-btn").on('touchend',function () {
            if (sound[audioindex].isload) {
                sound[audioindex].howl.seek(curtime);
            }
        });

        wx.onMenuShareTimeline({
            title: shareobj.title,
            link: shareobj.url,
            imgUrl: 'http://wap.nldou.com/comm/img/comm-logo.jpg',
            success: function () {
                sharecallback('timeline');
                return true;
            }
        });
        wx.onMenuShareAppMessage({
            title: shareobj.title,
            desc: '复旦大学社会学教授沈奕斐，为您解答家庭教育的各类问题，陪您共走育儿路',
            link: shareobj.url,
            imgUrl: 'http://wap.nldou.com/comm/img/comm-logo.jpg',
            type: 'link',
            success: function () {
                sharecallback('appmsg');
                return true;
            }
        });
    });
}();
